package com.ml.shs.controller;

import com.ml.shs.annotation.LoginAnnotation;
import com.ml.shs.repository.PhotoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/shs/photo")
public class PhotoGontroller {

    @Autowired
    PhotoRepository photoRepository;

    @PostMapping("/upload")
    @LoginAnnotation(name="没有登陆")
    public String add(@RequestParam("file") MultipartFile file) {
        String fileId = "";
        try {
            String fileName = file.getOriginalFilename();
            InputStream is = file.getInputStream();
            fileId = photoRepository.save(is, fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileId;
    }

    @GetMapping("/find/{fileId}")
    public void find(@PathVariable("fileId") String fileId, HttpServletRequest request, HttpServletResponse response) {
        GridFsResource gridFsResource = photoRepository.findPhoto(fileId);

        try {
            InputStream in = gridFsResource.getInputStream();
            ServletOutputStream outputStream = response.getOutputStream();

            byte[] data = new byte[1024];
            while (in.read(data)>0){
                outputStream.write(data);
            }
            in.close();

            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @GetMapping("/delete/{fileId}")
    @LoginAnnotation(name="没有登陆")
    public void delete(@PathVariable("fileId") String fileId) {
        photoRepository.deletePhoto(fileId);
    }
}
